﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AUV5.Web.Pages
{
    public partial class UserHome : PageBaseFrontend
    {
        public string serivceCount = string.Empty;  //服务个数
        public string userName = HttpContext.Current.Request["username"];
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(userName))
                {
                    BindData(AUV5.BLL.UserInfoBLL.Instance.GetUserIdByUserName(userName));
                }
                else
                {
                    Response.Redirect("~/Pages/Index.aspx");
                }
            }
            if (base.IsVerified)
            {
                hlUserProfile.Visible = base.VerifiedInfo.User.UserName == userName;
            }
        }

        #region##绑定用户基本信息
        /// <summary>
        /// 绑定用户基本信息
        /// 创建人：Wilson
        /// 创建时间：2011-10-26
        /// </summary>
        /// <param name="userId"></param>
        private void BindData(string userId)
        {
            //用户信息
            AUV5.Model.UserInfo user = AUV5.BLL.UserInfoBLL.Instance.GetDetail(userId);

            if (user != null)
            {
                imgUser.ImageUrl = user.PhotoPath;   //用户头像
                lblUserName.Text = user.UserName;   //用户名
                lblJoin.Text = base.GetTimeSpan(user.CreateDate);
                lblLastActivity.Text = base.GetTimeSpan(user.LastLogin);
                imgUserLevel.ImageUrl = new AUV5.BLL.AuvLevelBLL().GetUserLevelByUserId(user.UserID);

                lbGender.Text = (user.Gender == (int)Common.Enum.Gender.Man) ? "男" : "女";
                lbAddress.Text = BLL.GBADBLL.GetInstance().GetNameByCode(user.Province) + " " + BLL.GBADBLL.GetInstance().GetNameByCode(user.City);

                int totalRateCount = AUV5.BLL.ServiceInfoBLL.Instance.GetRateSumByUserId(user.UserID);

                if (totalRateCount > 0)
                {
                    double receRate = Convert.ToDouble(AUV5.BLL.ServiceInfoBLL.Instance.GetGoodRateSumByUserId(userId)) / Convert.ToDouble(totalRateCount);
                    lblReceivedRate.Text = receRate.ToString("0%");
                }
                else
                {
                    lblReceivedRate.Text = "-";
                }

                string contractUrl = "/Pages/MessageShow.aspx?userID=" + user.UserID;
                if (base.IsVerified)                               //收藏
                {
                    if (base.VerifiedUserID == user.UserID)
                    {
                        lbtnContract.Visible = false;
                    }
                    lbtnContract.PostBackUrl = contractUrl;
                }
                else
                {
                    lbtnContract.PostBackUrl = "/Pages/Login.aspx?returnURL=" + contractUrl;
                }

                lblDesc.Text = user.Description;   //用户描述

                IList<AUV5.Model.ServiceInfo> list = AUV5.BLL.ServiceInfoBLL.Instance.GetServiceListByUserId(user.UserID, Convert.ToInt32(AUV5.Common.Enum.ServiceStatus.Active));

                serivceCount = Convert.ToString(list.Count);

                repService.DataSource = list;
                repService.DataBind();

                //用户没有发布服务，显示引导层(Wilson 2012-2-27)
                if (list.Count > 0)
                {
                    noResultPanel.Visible = false;
                }
                else
                {
                    noResultPanel.Visible = true;
                }

                //rpServiceInfo.DataSource = list;
                //rpServiceInfo.DataBind();

                //用户的收藏
                //bindFavorite();



            }
            else
            {
                Response.Redirect("~/Pages/Index.aspx");
            }
        }

        //private void bindFavorite()
        //{
        //    Model.NetPager pager = new Model.NetPager();
        //    pager.TableName = "Favorite";
        //    pager.PrimaryKey = "FavoriteID";
        //    pager.PageSize = AspNetPager1.PageSize;
        //    pager.PageIndex = AspNetPager1.CurrentPageIndex;
        //    pager.Order = "CreateDate desc,FavoriteID asc";
        //    pager.SortType = (int)Common.Enum.SortType.Multi;
        //    pager.Where = "UserID='" + BLL.UserInfoBLL.Instance.GetUserIdByUserName(userName) + "' and State = " + Convert.ToInt32(AUV5.Common.Enum.auvState.Enabled) + " and IsDel = " + Convert.ToInt32(AUV5.Common.Enum.auvDel.NotDel);

        //    IList<Model.ServiceInfo> list = BLL.FavoriteBLL.Instance.GetPagedFavoriteServiceList(pager);
        //    //UCServiceList1.UserID = base.VerifiedUserID;
        //    UCServiceList1.Bind(list);
        //}
        #endregion

        #region##服务信息repeater项绑定后激发事件
        /// <summary>
        /// 服务信息repeater项绑定后激发事件
        /// 创建人：Wilson
        /// 创建时间：2011-10-26
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rpServiceInfo_DataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                Label lbl = e.Item.FindControl("lblId") as Label;

                AUV5.Model.ServiceInfo service = AUV5.BLL.ServiceInfoBLL.Instance.GetDetail(lbl.Text);

                Repeater rpKeys = e.Item.FindControl("rpKeys") as Repeater;   //关键字

                Repeater repAttach = e.Item.FindControl("repAttach") as Repeater;  //附件

                if (service != null)
                {
                    Label lblReceivedRate = e.Item.FindControl("lblReceivedRate") as Label;    //好评率
                    Label lblQueueCount = e.Item.FindControl("lblQueueCount") as Label;   //等待队列
                    Label lblJoin = e.Item.FindControl("lblJoin") as Label;
                    Label lblCreateTime = e.Item.FindControl("lblCreateTime") as Label;  //底部创建时间
                    Label lblFavCount = e.Item.FindControl("lblFavCount") as Label;   //底部收藏数
                    LinkButton lbtnOrder = e.Item.FindControl("lbtnOrder") as LinkButton;   //订单按钮
                    Label lblSellerReceivedRate = e.Item.FindControl("lblSellerReceivedRate") as Label;  //卖家好评率                  
                    //LinkButton lbtnCollection = e.Item.FindControl("lbtnCollection") as LinkButton;  //收藏按钮
                    ImageButton imgBtnContractSeller = e.Item.FindControl("imgBtnContractSeller") as ImageButton;  //联系按钮
                    Label lblFbUserCount = e.Item.FindControl("lblFbUserCount") as Label;   //多少人分享经验
                    ImageButton imgBtnEdit = e.Item.FindControl("imgBtnEdit") as ImageButton;  //编辑按钮

                    lblFbUserCount.Text = Convert.ToString(AUV5.BLL.FeedBackBLL.Instance.GetFeebBackDistinct(service.ServiceID));

                    lbtnOrder.Text = service.Price.ToString("0");

                    int totalSellerRateCount = AUV5.BLL.ServiceInfoBLL.Instance.GetRateSumByUserId(service.UserID);

                    if (totalSellerRateCount > 0)
                    {
                        double sellerReceRate = Convert.ToDouble(AUV5.BLL.ServiceInfoBLL.Instance.GetGoodRateSumByUserId(service.UserID)) / Convert.ToDouble(totalSellerRateCount);
                        lblSellerReceivedRate.Text = sellerReceRate.ToString("0%");
                    }
                    else
                    {
                        lblSellerReceivedRate.Text = "-";
                    }

                    string contractUrl = "~/Pages/MessageShow.aspx?userID=" + service.UserID + "&serviceID=" + service.ServiceID;

                    if (base.IsVerified)
                    {
                        if (base.VerifiedUserID != service.UserID)
                        {
                            bool flag = AUV5.BLL.FavoriteBLL.Instance.Contain(service.ServiceID, base.VerifiedUserID);
                            //lbtnCollection.CommandName = flag ? "UnSave" : "Save";
                            //lbtnCollection.Text = flag ? "取消收藏" : "收藏";
                        }
                        else
                        {
                            imgBtnContractSeller.Visible = false;
                            //lbtnCollection.Visible = false;
                            lbtnOrder.Visible = false;
                            imgBtnEdit.Visible = true;
                        }
                        imgBtnContractSeller.PostBackUrl = contractUrl;
                    }
                    else
                    {
                        //lbtnCollection.Visible = false;
                        imgBtnContractSeller.PostBackUrl = "~/Pages/Login.aspx?returnURL=" + contractUrl;
                    }


                    int totalRate = service.GoodRating + service.BadRating;
                    if (totalRate > 0)
                    {
                        double receRate = Convert.ToDouble(service.GoodRating) / Convert.ToDouble(totalRate);
                        lblReceivedRate.Text = receRate.ToString("0%");
                    }
                    else
                    {
                        lblReceivedRate.Text = "-";
                    }

                    int queueCount = AUV5.BLL.OrderItemBLL.Instance.GetOrderItemQuantityCountByCondition(service.ServiceID, Convert.ToInt32(AUV5.Common.Enum.OrderState.Payment));

                    lblQueueCount.Text = queueCount.ToString();             //队列

                    lblJoin.Text = base.GetTimeSpan(service.CreateDate);   //加入时间

                    lblCreateTime.Text = base.GetTimeSpan(service.CreateDate);

                    lblFavCount.Text = AUV5.BLL.FavoriteBLL.Instance.GetSFavCountByServiceId(service.ServiceID).ToString();



                    rpKeys.DataSource = AUV5.BLL.KeywordBLL.Instance.GetKeyListByServiceId(service.ServiceID);
                    rpKeys.DataBind();

                    repAttach.DataSource = BLL.ServiceAttachmentBLL.Instance.GetListByServiceID(4, service.ServiceID); ;
                    repAttach.DataBind();
                }
            }
        }
        #endregion

        #region## 服务信息repeater生成事件
        /// <summary>
        /// 服务信息repeater生成事件
        /// 创建人：Wilson
        /// 创建时间：2011-10-26
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void rpServiceInfo_Command(object source, RepeaterCommandEventArgs e)
        {
            string id = string.Empty;
            //LinkButton lbtnCollection = e.Item.FindControl("lbtnCollection") as LinkButton;  //收藏按钮
            switch (e.CommandName)
            {
                case "orderThis":
                    id = Convert.ToString(e.CommandArgument);
                    if (base.IsVerified)
                    {
                        string returnurl = BLL.OrderInfoBLL.Instance.OrderService(id, base.VerifiedUserID, null);
                        Response.Redirect(returnurl, false);
                    }
                    else
                    {
                        Response.Redirect("~/Pages/Login.aspx?returnURL=" + Request.Url);
                    }
                    #region 注释代码  Moved to OrderInfoBLL
                    //if (base.IsVerified)
                    //{
                    //    AUV5.Model.ServiceInfo service = AUV5.BLL.ServiceInfoBLL.Instance.GetDetail(id);

                    //    if (service != null)
                    //    {
                    //        AUV5.Model.OrderInfo info = new Model.OrderInfo();
                    //        info.BeginDate = DateTime.Now;
                    //        info.Buyer = base.VerifiedUserID;
                    //        info.CreateDate = DateTime.Now;
                    //        info.EndDate = DateTime.Now;
                    //        info.IsDel = Convert.ToInt32(AUV5.Common.Enum.auvDel.NotDel);
                    //        info.OrderID = Guid.NewGuid().ToString();
                    //        info.Payment = 0;
                    //        info.Remark = "";
                    //        info.Seller = service.UserID;
                    //        info.State = Convert.ToInt32(AUV5.Common.Enum.auvState.Enabled);
                    //        info.StatusID = Convert.ToInt32(AUV5.Common.Enum.OrderState.Default).ToString();
                    //        info.Total = 5;
                    //        info.UpdateDate = DateTime.Now;

                    //        AUV5.BLL.OrderInfoBLL.Instance.Add(info);

                    //        AUV5.Model.OrderItem item = new Model.OrderItem();
                    //        item.BeginDate = DateTime.Now;
                    //        item.CreateDate = DateTime.Now;
                    //        item.EndDate = DateTime.Now;
                    //        item.IsDel = Convert.ToInt32(AUV5.Common.Enum.auvDel.NotDel);
                    //        item.OrderID = info.OrderID;
                    //        item.OrderItemID = Guid.NewGuid().ToString();
                    //        item.Quantity = 1;
                    //        item.ServiceID = service.ServiceID;
                    //        item.State = Convert.ToInt32(AUV5.Common.Enum.auvState.Enabled);
                    //        item.UpdateDate = DateTime.Now;
                    //        item.Price = 5;

                    //        AUV5.BLL.OrderItemBLL.Instance.Add(item);

                    //        Response.Redirect("~/Alipay/Default.aspx?OrderID=" + info.OrderID);
                    //    }
                    //}
                    //else
                    //{
                    //    Response.Redirect("~/Pages/Login.aspx?returnURL=" + Request.Url);
                    //}
                    #endregion

                    break;
                case "Save":
                    id = Convert.ToString(e.CommandArgument);
                    if (base.IsVerified)
                    {
                        Model.Favorite fav = new Model.Favorite();
                        fav.ServiceID = id;
                        fav.UserID = base.VerifiedUserID;
                        fav.CreateDate = DateTime.Now;
                        fav.BeginDate = DateTime.Now;

                        if (!BLL.FavoriteBLL.Instance.Contain(fav.ServiceID, fav.UserID))
                        {
                            fav.FavoriteID = Guid.NewGuid().ToString();
                            BLL.FavoriteBLL.Instance.Add(fav);
                            //lbtnCollection.CommandName = "UnSave";
                            //lbtnCollection.Text = "取消收藏";
                        }

                    }
                    else
                    {
                        Response.Redirect("~/Pages/Login.aspx?returnURL=" + Request.Url);
                    }
                    break;
                case "UnSave":
                    id = Convert.ToString(e.CommandArgument);
                    if (base.IsVerified)
                    {
                        Model.Favorite fav = new Model.Favorite();
                        fav.ServiceID = id;
                        fav.UserID = base.VerifiedUserID;
                        fav.CreateDate = DateTime.Now;
                        fav.BeginDate = DateTime.Now;

                        BLL.FavoriteBLL.Instance.Delete(fav);

                        //lbtnCollection.CommandName = "Save";
                        //lbtnCollection.Text = "收藏";
                    }
                    else
                    {
                        Response.Redirect("~/Pages/Login.aspx?returnURL=" + Request.Url);
                    }
                    break;
                case "editThis":
                    id = Convert.ToString(e.CommandArgument);
                    Response.Redirect("~/Pages/ServiceEdit.aspx?serviceID=" + id);
                    break;
            }
        }
        #endregion

        //protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        //{
        //    bindFavorite();
        //}

    }
}